<?php
require_once dirname(__FILE__).'/../classes/google-api/src/Google_Client.php';
require_once dirname(__FILE__).'/../classes/google-api/src/contrib/Google_DriveService.php';

class GDrive {

	private static $sharedFolderPathId = "0BxDtJIvMMIOBZW9NX1ZldlVfTVk";
	private static $clientId = '150831902391-g05k146a8n65q70j13k5m5liov8cqlv6.apps.googleusercontent.com';
	private static $clientSecret = 'FV9HUGg8q5MA3TQHHpyJP2BS';
	
	private static function getTokenFilePath() {
		return dirname(__FILE__).'/token.json';
	}

	static function sendBackupFiles($filesToSendPathArray, $folderName) {

		$client = new Google_Client();
		// Get your credentials from the console
		$client->setClientId(self::$clientId);
		$client->setClientSecret(self::$clientSecret);
		$client->setRedirectUri('com.example.mimemank.com');
		$client->setScopes(array('https://www.googleapis.com/auth/drive'));

		$service = new Google_DriveService($client);


		/*
		$authUrl = $client->createAuthUrl();


		//Request authorization
		print "Please visit:\n$authUrl\n\n";
		print "Please enter the auth code:\n";
		$authCode = trim(fgets(STDIN));

		// Exchange authorization code for access token
		$accessToken = $client->authenticate($authCode);
		file_put_contents('token.json', $accessToken);
		/**/

		$client->setAccessToken(file_get_contents(self::getTokenFilePath()));

		$parentFolder = new Google_ParentReference();
		$parentFolder->setId(self::$sharedFolderPathId);
		
		//folder creation
		$folder = new Google_DriveFile();
		$folder->setTitle($folderName);
		$folder->setDescription($folderName);
		$folder->setMimeType(self::getMimeType($folderName));
			
		$folder->setParents(array($parentFolder));
		
		$insertFolderResult = $service->files->insert($folder, array(
				'mimeType' => self::getMimeType($folderName),
		));
		
		$parentFiles = new Google_ParentReference();
		$parentFiles->setId($insertFolderResult['id']);
		
		foreach ($filesToSendPathArray as $fileToSendPath) {
		
			//Insert a file
			$file = new Google_DriveFile();
			$file->setTitle(basename($fileToSendPath));
			$file->setDescription($fileToSendPath);
			$file->setMimeType(self::getMimeType($fileToSendPath));
			
			$file->setParents(array($parentFiles));
	
			$data = file_get_contents($fileToSendPath);
	
			$insertResultArray[] = $service->files->insert($file, array(
			      'data' => $data,
			      'mimeType' => self::getMimeType($fileToSendPath),
			    ));
		}
		
		return $insertFolderResult;
	}
	
	private static function getMimeType($filename)  {
		switch (trim(pathinfo($filename, PATHINFO_EXTENSION))) {
			case "zip":
				$mimeType = 'application/zip, application/octet-stream';
				break;
			case "sql":
			case "txt":
				$mimeType = 'text/plain';
				break;
			default:
				$mimeType = 'application/vnd.google-apps.folder';
				break;
		}
		return $mimeType;
	}
}
